package com.android.baseconfig.data.http.retrofit2.converter;

import com.android.baseconfig.base.BaseApiResult;
import com.android.baseconfig.data.http.retrofit2.exception.ApiException;
import com.android.baseconfig.data.http.retrofit2.exception.HttpErrorCode;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        if (adapter != null) {
        }

        try {
            JsonReader jsonReader = gson.newJsonReader(value.charStream());
            T data = adapter.read(jsonReader);
            if (data == null) {
                throw new ApiException(HttpErrorCode.UNKNOWN, HttpErrorCode.UNKNOWN_STRING + ":" + value.string());
            }
            if (data instanceof BaseApiResult) {
                BaseApiResult apiResult = (BaseApiResult) data;
                if (!ApiException.isOk(apiResult.status)) {
                    //根据HeT服务器定义，code != 0表示错误
                    throw new ApiException(apiResult.status, apiResult.message);
                }
                /*if (apiResult != null && apiResult.data != null && apiResult.data instanceof AuthModel) {
                    TokenManager.getInstance().setAuthModel((AuthModel) apiResult.getData());
                }*/
            }
            return data;
        } finally {
            value.close();
        }
    }

    /*@Override
    public T convert(ResponseBody value) throws IOException {
        if (adapter != null) {
        }
        JsonReader jsonReader = gson.newJsonReader(value.charStream());
        try {
            T data = adapter.read(jsonReader);
            if (data == null)
                throw new ServerException(-1, "server back data is null");
            if (data instanceof ApiResult) {
                ApiResult apiResult = (ApiResult) data;
                if (!ApiException.isOk(apiResult)) {
                    //根据HeT服务器定义，code != 0表示错误
                    throw new ServerException(apiResult.getCode(), apiResult.getMsg() == null ? "unknow error" : apiResult.getMsg());
                }
            }
            return data;
        } finally {
            value.close();
        }
    }*/
}
